<template>
  <div class="vehicle-add">
    <div class="header-with-back">
      <el-button type="text" @click="goBack" class="back-button">
        <el-icon><ArrowLeft /></el-icon> 返回
      </el-button>
      <h2>车辆增添</h2>
    </div>
    <el-form
        :model="addForm"
        :rules="formRules"
        ref="addFormRef"
        label-width="100px"
        class="add-form"
    >
      <el-form-item label="类型" prop="typeId">
        <el-select v-model="addForm.typeId" placeholder="请选择车辆类型" size="small">
          <el-option label="轿车" value="1" />
          <el-option label="SUV" value="2" />
          <el-option label="跑车" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input v-model="addForm.brand" placeholder="请输入品牌" size="small"></el-input>
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input v-model="addForm.model" placeholder="请输入型号" size="small"></el-input>
      </el-form-item>
      <el-form-item label="车牌号" prop="licensePlate">
        <el-input v-model="addForm.licensePlate" placeholder="请输入车牌号" size="small"></el-input>
      </el-form-item>
      <el-form-item label="颜色" prop="color">
        <el-input v-model="addForm.color" placeholder="请输入颜色" size="small"></el-input>
      </el-form-item>
      <el-form-item label="日租价格" prop="dailyRent">
        <el-input-number
            v-model="addForm.dailyRent"
            :min="0"
            :precision="2"
            controls-position="right"
            size="small"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="addForm.status" placeholder="请选择状态" size="small">
          <el-option label="空闲" :value="0"></el-option>
          <el-option label="已租" :value="1"></el-option>
          <el-option label="维修" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="车辆图片" prop="images">
        <el-upload
            :http-request="get_image"
            list-type="picture-card"
            :file-list="addForm.images"
            :on-preview="handleImagePreview"
            :on-remove="handleImageRemove"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeImageUpload"
            multiple
            accept="image/*"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" size="small">增添</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { Plus, ArrowLeft } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { insertCar } from "@/api/car";
import axios from "axios";
import { useMerchantInfoStore } from '@/stores/merchantInfo'
const router = useRouter()
// 在 <script setup> 顶部添加
const merchantStore = useMerchantInfoStore()
const merchantId = merchantStore.merchantInfo?.id || ''

// 修正：从el-upload传递的参数中提取真正的File对象
const get_image = async (uploadParams) => {
  try {
    // 关键：uploadParams.file才是真正的文件对象
    const file = uploadParams.file;
    const formData = new FormData();
    formData.append('file', file); // 这里才是正确的文件对象

    const response = await axios.post(
        '/api/file/upload1.do',
        formData // 不手动设置Content-Type，由浏览器自动处理
    );

    console.log('上传成功', response.data);
    // 调用el-upload的成功回调（必须调用，否则组件会显示上传中）
    uploadParams.onSuccess(response.data);
    image_url = response.data.message;
    return response.data;
  } catch (error) {
    console.error('上传失败', error);
    // 调用el-upload的错误回调
    uploadParams.onError(error);
    throw error;
  }
};
let image_url="";
const addForm = reactive({
  merchantId: merchantId,
  typeId: '',
  brand: '',
  model: '',
  licensePlate: '',
  color: '',
  dailyRent: 0,
  status: '',
  images: []
})

const addFormRef = ref(null)

const formRules = {
  typeId: [{ required: true, message: '请选择车辆类型', trigger: 'change' }],
  brand: [{ required: true, message: '请输入车辆品牌', trigger: 'blur' }],
  model: [{ required: true, message: '请输入车辆型号', trigger: 'blur' }],
  licensePlate: [{ required: true, message: '请输入车牌号码', trigger: 'blur' }],
  color: [{ required: true, message: '请输入车辆颜色', trigger: 'blur' }],
  dailyRent: [{ required: true, message: '请输入日租价格', trigger: 'blur' }],
  status: [{ required: true, message: '请选择车辆状态', trigger: 'change' }],
  images: [{ required: true, message: '请上传车辆图片', trigger: 'change' }]
}

const goBack = () => {
  router.push('/carList')
}

const submitForm = async () => {
  try {
    // 1. 表单验证
    await addFormRef.value.validate()

    // 2. 准备表单数据（注意格式要求）
    const formData = new URLSearchParams()
    formData.append('merchantId', addForm.merchantId)
    formData.append('typeId', addForm.typeId)
    formData.append('brand', addForm.brand)
    formData.append('model', addForm.model)
    formData.append('licensePlate', addForm.licensePlate)
    formData.append('color', addForm.color)
    formData.append('dailyRent', addForm.dailyRent)
    formData.append('status', addForm.status)
    formData.append('images', image_url)

    console.log('提交数据:', Object.fromEntries(formData))

    // 3. 调用API接口
    const res = await insertCar(formData)
    console.log('接口响应:', res)
    // 4. 处理响应
    if (res?.code === 200) {
      ElMessage.success('车辆添加成功')
      router.push('/carList')
    } else {
      ElMessage.error(res?.message || '添加失败，请检查数据')
    }
  } catch (error) {
    console.error('提交出错:', error)
    if (error.response) {
      // 处理HTTP错误状态码
      const msg = error.response.data?.message || error.response.statusText
      ElMessage.error(`服务器错误: ${msg}`)
    } else if (error.request) {
      ElMessage.error('网络错误，请检查连接')
    } else {
      ElMessage.error(error.message || '未知错误')
    }
  }
}

const resetForm = () => {
  addFormRef.value.resetFields()
  addForm.images = []
}

const handleImagePreview = (file) => {
  ElMessageBox.open({
    title: '图片预览',
    message: `<img src="${file.url}" alt="预览图片" style="max-width: 100%">`,
    dangerouslyUseHTMLString: true
  })
}

const handleImageRemove = (file, fileList) => {
  addForm.images = fileList
}

const handleUploadSuccess = (response, file, fileList) => {
  addForm.images = fileList.map(item => ({
    name: item.name,
    url: item.response?.url || item.url
  }))
  ElMessage.success('图片上传成功')
}

const handleUploadError = () => {
  ElMessage.error('图片上传失败，请重试')
}

const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
    return false
  }
  return true
}

</script>

<style scoped>
.vehicle-add {
  max-width: 500px;
  margin: 5px auto;
  padding: 15px;
  background-color: #fff;
  border-radius: 6px;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.1);
}

.header-with-back {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.back-button {
  margin-right: 15px;
  padding: 0;
  font-size: 13px;
}

.header-with-back h2 {
  font-size: 16px;
  margin: 0;
}

.add-form {
  display: flex;
  flex-direction: column;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-button {
  margin-top: 15px;
  font-size: 13px;
}

.el-upload {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 80px;
  height: 80px;
}

:deep(.el-upload--picture-card) {
  width: 80px;
  height: 80px;
  line-height: 80px;
}
</style>